package com.atguigu.tingshu.user.api;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.atguigu.tingshu.account.client.UserAccountFeignClient;
import com.atguigu.tingshu.common.annotation.GuiGuLogin;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.user.service.UserInfoService;

import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.net.http.HttpClient;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Tag(name = "微信授权登录接口")
@RestController
@RequestMapping("/api/user/wxLogin")
@Slf4j
public class WxLoginApiController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserAccountFeignClient userAccountFeignClient;

    @Autowired
    private RabbitService rabbitService;

    @Operation(summary = "小程序授权登录")
    @GetMapping("/wxLogin/{code}")
    @SneakyThrows
    public Result wxLogin(@PathVariable(value = "code") String code){
        //1 获取前端传递的code值
        //2  拿着code + 小程序id  + 秘钥 请求微信服务器接口  得到openid
        WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
        String openid = sessionInfo.getOpenid();

        //3  根据openid 判断是否是第一次登录

        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getWxOpenId,openid);
        UserInfo userInfo = userInfoService.getOne(wrapper);
        if(userInfo==null){
            //表示是第一次登录
            //如果是第一次登录 要添加用户信息
            userInfo = new UserInfo();
            userInfo.setWxOpenId(openid);
            userInfo.setNickname("听友"+System.currentTimeMillis());
            userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            userInfoService.save(userInfo);
            //初始化账户
            //方法一：远程调用  在service-account 创建初始化接口
            //在serivice-user进行远程调用实现
//            userAccountFeignClient.initUserAccount(userInfo.getId());


            //方式二：异步方式  消息队列实现
            //在service-user端发送消息，在service-account端接收消息
            rabbitService.sendMessage(MqConst.EXCHANGE_ACCOUNT,
                    MqConst.ROUTING_ACCOUNT_MINUS,userInfo.getId());
        }

        //4   生成token  把用户信息存储到redis中
        //设置redis的过期时间
        //redis的key是token  value是用户信息
        //生成唯一的token
        String token = UUID.randomUUID().toString().replaceAll("-","");

        redisTemplate.opsForValue().set(token,userInfo,24, TimeUnit.HOURS);


        //5  返回token
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        Object token1 = map.get("token");
        System.out.println(token1);
        return Result.ok(map);
    }

    //获取用户信息
    @GuiGuLogin
    @Operation(summary = "获取用户信息")
    @GetMapping("/getUserInfo")
    public Result getUserInfo(){
        //获取登录用户id
        Long userId = AuthContextHolder.getUserId();
//        UserInfo userInfo = userInfoService.getById(userId);
       UserInfoVo userInfoVo =  userInfoService.getUserInfo(userId);
        return Result.ok(userInfoVo);
    }

    //更新用户信息
    @GuiGuLogin
    @Operation(summary = "更新用户信息")
    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody UserInfoVo userInfoVo){
        //获取登录用户id
        Long userId = AuthContextHolder.getUserId();
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
//        BeanUtils.copyProperties(userInfoVo,userInfo);
        userInfo.setNickname(userInfoVo.getNickname());
        userInfo.setAvatarUrl(userInfoVo.getAvatarUrl());
        userInfoService.updateById(userInfo);
        return Result.ok();
    }

}
